import React, { useState, useEffect } from 'react';
import { 
  View, 
  Text, 
  StyleSheet, 
  ScrollView, 
  ActivityIndicator, 
  Image,
  TouchableOpacity
} from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { Ionicons } from '@expo/vector-icons';

import { getNowWeather, get3DayForecast, getLifeIndices } from '../services/weatherService';
import WeatherIcon from '../components/WeatherIcon';
import ForecastItem from '../components/ForecastItem';
import LifeIndexItem from '../components/LifeIndexItem';

const WeatherDetailScreen = ({ route, navigation }) => {
  const { city, locationId } = route.params;
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [currentWeather, setCurrentWeather] = useState(null);
  const [forecast, setForecast] = useState(null);
  const [lifeIndices, setLifeIndices] = useState(null);

  // 设置标题
  useEffect(() => {
    navigation.setOptions({
      title: city?.name || '天气详情'
    });
  }, [city, navigation]);

  // 获取天气数据
  useEffect(() => {
    const loadWeatherData = async () => {
      try {
        setLoading(true);
        setError(null);
        
        // 并行获取天气数据
        const [nowResponse, forecastResponse, indicesResponse] = await Promise.all([
          getNowWeather(city),
          get3DayForecast(city),
          getLifeIndices(city)
        ]);
        
        setCurrentWeather(nowResponse.now);
        setForecast(forecastResponse.daily);
        setLifeIndices(indicesResponse.daily);
        
      } catch (err) {
        console.error('加载天气数据失败:', err);
        setError('获取天气数据失败，请检查网络连接');
      } finally {
        setLoading(false);
      }
    };

    loadWeatherData();
  }, [locationId]);

  // 获取背景颜色（根据天气状况和时间）
  const getBackgroundColors = () => {
    if (!currentWeather) return ['#4c669f', '#3b5998', '#192f6a'];
    
    const weatherCode = parseInt(currentWeather.icon);
    const hour = new Date().getHours();
    const isNight = hour < 6 || hour > 18;
    
    // 晴天
    if (weatherCode === 100) {
      return isNight ? ['#1a2a6c', '#2a3a7c', '#3b4a8c'] : ['#00d2ff', '#3a7bd5', '#00d2ff'];
    }
    // 多云
    else if (weatherCode >= 101 && weatherCode <= 104) {
      return isNight ? ['#283E51', '#4B79A1'] : ['#7F7FD5', '#86A8E7', '#91EAE4'];
    }
    // 雨天
    else if (weatherCode >= 300 && weatherCode <= 399) {
      return ['#373B44', '#4286f4'];
    }
    // 雪天
    else if (weatherCode >= 400 && weatherCode <= 499) {
      return ['#8e9eab', '#eef2f3'];
    }
    // 雾霾
    else if (weatherCode >= 500 && weatherCode <= 599) {
      return ['#606c88', '#3f4c6b'];
    }
    // 默认
    return ['#4c669f', '#3b5998', '#192f6a'];
  };

  // 渲染加载状态
  if (loading) {
    return (
      <View style={styles.centerContainer}>
        <ActivityIndicator size="large" color="#0080ff" />
        <Text style={styles.loadingText}>加载天气数据中...</Text>
      </View>
    );
  }

  // 渲染错误状态
  if (error) {
    return (
      <View style={styles.centerContainer}>
        <Ionicons name="cloud-offline" size={64} color="#888" />
        <Text style={styles.errorText}>{error}</Text>
        <TouchableOpacity style={styles.retryButton} onPress={() => navigation.goBack()}>
          <Text style={styles.retryButtonText}>返回</Text>
        </TouchableOpacity>
      </View>
    );
  }

  return (
    <LinearGradient colors={getBackgroundColors()} style={styles.container}>
      <ScrollView contentContainerStyle={styles.scrollContent}>
        {/* 城市和更新时间 */}
        <View style={styles.header}>
          <Text style={styles.cityName}>{city?.name || '未知城市'}</Text>
          <Text style={styles.cityInfo}>
            {city?.adm2 && `${city.adm2}, `}{city?.adm1 || ''}, {city?.country || ''}
          </Text>
          <Text style={styles.updateTime}>
            更新时间: {currentWeather?.obsTime.substring(11, 16) || ''}
          </Text>
        </View>
        
        {/* 当前天气 */}
        {currentWeather && (
          <View style={styles.currentWeather}>
            <WeatherIcon code={currentWeather.icon} size={80} />
            <Text style={styles.temperature}>{currentWeather.temp}°</Text>
            <Text style={styles.weatherText}>{currentWeather.text}</Text>
            <View style={styles.weatherDetails}>
              <View style={styles.weatherDetailItem}>
                <Ionicons name="water-outline" size={18} color="#fff" />
                <Text style={styles.weatherDetailText}>湿度 {currentWeather.humidity}%</Text>
              </View>
              <View style={styles.weatherDetailItem}>
                <Ionicons name="speedometer-outline" size={18} color="#fff" />
                <Text style={styles.weatherDetailText}>气压 {currentWeather.pressure}hPa</Text>
              </View>
              <View style={styles.weatherDetailItem}>
                <Ionicons name="compass-outline" size={18} color="#fff" />
                <Text style={styles.weatherDetailText}>
                  {currentWeather.windDir} {currentWeather.windScale}级
                </Text>
              </View>
            </View>
          </View>
        )}
        
        {/* 未来天气预报 */}
        {forecast && (
          <View style={styles.forecastContainer}>
            <Text style={styles.sectionTitle}>未来天气预报</Text>
            <View style={styles.forecastList}>
              {forecast.map((day, index) => (
                <ForecastItem key={index} data={day} />
              ))}
            </View>
          </View>
        )}
        
        {/* 生活指数 */}
        {lifeIndices && (
          <View style={styles.indicesContainer}>
            <Text style={styles.sectionTitle}>生活指数</Text>
            <View style={styles.indicesList}>
              {lifeIndices.map((index, i) => (
                <LifeIndexItem key={i} data={index} />
              ))}
            </View>
          </View>
        )}
      </ScrollView>
    </LinearGradient>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollContent: {
    flexGrow: 1,
    paddingBottom: 20,
  },
  centerContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f5f5f5',
  },
  loadingText: {
    marginTop: 10,
    fontSize: 16,
    color: '#666',
  },
  errorText: {
    marginTop: 10,
    fontSize: 16,
    color: '#666',
    textAlign: 'center',
    paddingHorizontal: 30,
  },
  retryButton: {
    marginTop: 20,
    paddingVertical: 10,
    paddingHorizontal: 20,
    backgroundColor: '#0080ff',
    borderRadius: 5,
  },
  retryButtonText: {
    color: '#fff',
    fontSize: 16,
  },
  header: {
    alignItems: 'center',
    paddingTop: 20,
    paddingBottom: 10,
  },
  cityName: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#fff',
  },
  cityInfo: {
    fontSize: 14,
    color: 'rgba(255, 255, 255, 0.8)',
    marginTop: 5,
  },
  updateTime: {
    fontSize: 14,
    color: 'rgba(255, 255, 255, 0.7)',
    marginTop: 5,
  },
  currentWeather: {
    alignItems: 'center',
    paddingVertical: 20,
  },
  temperature: {
    fontSize: 72,
    fontWeight: '200',
    color: '#fff',
  },
  weatherText: {
    fontSize: 20,
    color: '#fff',
    marginTop: 5,
  },
  weatherDetails: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    width: '100%',
    marginTop: 20,
    paddingHorizontal: 20,
  },
  weatherDetailItem: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  weatherDetailText: {
    color: '#fff',
    marginLeft: 5,
    fontSize: 14,
  },
  forecastContainer: {
    marginTop: 20,
    paddingHorizontal: 20,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: 10,
  },
  forecastList: {
    backgroundColor: 'rgba(255, 255, 255, 0.2)',
    borderRadius: 10,
    padding: 15,
  },
  indicesContainer: {
    marginTop: 20,
    paddingHorizontal: 20,
  },
  indicesList: {
    backgroundColor: 'rgba(255, 255, 255, 0.2)',
    borderRadius: 10,
    padding: 15,
  },
});

export default WeatherDetailScreen;